package com.alpha.framework.http.protocol;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Map;
import java.util.Set;
import android.os.SystemClock;
import com.alpha.framework.bean.BaseInfo;
import com.alpha.framework.http.HttpHelper;
import com.alpha.framework.http.HttpHelper.HttpResult;
import com.alpha.framework.ui.LoadingPage.LoadResult;
import com.alpha.framework.utils.FileUtils;
import com.alpha.framework.utils.GsonUtils;
import com.alpha.framework.utils.IOUtils;
import com.alpha.framework.utils.LogUtils;
import com.alpha.framework.utils.StringUtils;

public abstract class BaseProtocol<Data> {
//	public static final String cachePath = "";

	/** 请求服务器的josn*/
	private String mGetParames="";
	private BaseInfo mPostParames=null;
	
	public BaseProtocol(){}
	
	/**
	 * 需要传递 getParames 子类需要实现该构造
	 * @param getParames get请求参数
	 */
	public BaseProtocol(Map<String, String> getParamesMap){
		this(getParamesMap,null);
	}
	
	/**
	 * 需要传递 postParames 子类需要实现该构造
	 * @param postParames post请求参数
	 */
	public BaseProtocol(BaseInfo postParames){
		this(null,postParames);
	}
	
	/**
	 * 需要传递 getParames和postParames 子类需要实现该构造
	 * @param getParames get请求参数
	 * @param postParames post请求参数
	 */
	public BaseProtocol(Map<String, String> getParamesMap,BaseInfo postParames){
		if(null!=getParamesMap)
			this.mGetParames=map2getParames(getParamesMap);
		if(null!=postParames){
			postParames.response=getKey();
			this.mPostParames=postParames;
		}
	}
	
	/**
	 * 将map集合转成 get请求参数
	 * @param getParamesMap
	 * @return
	 */
	private String map2getParames(Map<String, String> getParamesMap){
		StringBuilder sb = new StringBuilder();
		if(null!=getParamesMap){
			Set<String> keySet = getParamesMap.keySet();
			for (String key : keySet) {
				sb.append("&"+key+"="+getParamesMap.get(key));
			}
		}
		return sb.toString();
	}
	
/*	*//** 加载协议 *//*
	public Data load(int index) {
		SystemClock.sleep(1000);// 休息1秒，防止加载过快，看不到界面变化效果
		String json = null;
		// 1.从本地缓存读取数据，查看缓存时间
		json = loadFromLocal(index);
		// 2.如果缓存时间过期，从网络加载
		if (StringUtils.isEmpty(json)) { 
			json = loadFromNet(index);
			if (json == null) {
				// 网络出错
				return null;
			}
			else {
				// 3.把数据保存到本地保存到本地
				saveToLocal(json, index);
			}
		}
		return parseFromJson(json);
	}*/
	
	/** 加载协议 */
	public Data load(int index) {
		SystemClock.sleep(500);// 休息1秒，防止加载过快，看不到界面变化效果
		String json = null;
		if(null==getPostParames()){
			json = loadFromNet(index);
		}else{
			json = loadFromNet(index,getPostParames());
		}
		
		if (json == null) {
			// 网络出错
			return null;
		}
		LogUtils.d(getKey()+"=接口请求返回的json="+json);
		//防止解析json 出错 程序蹦
		Data dataInfo = null;
		try {
			dataInfo = parseFromJson(json);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(null==dataInfo)
			new RuntimeException("服务器返回的json格式错误："+json);
		return dataInfo;
	}

	/**
	 * 检查服务器返回的json是成功或是失败
	 * networkUtils.access方式请求 json检查
	 * @param 不能为 null对象
	 * @return
	 */
	public boolean checkJson(Data data){
		if(data instanceof BaseInfo){
//			LogUtils.d("checkJson="+getKey().substring(getKey().indexOf("/")+1)+"   ==  "+getKey().substring(getKey().indexOf("/")+1).equals(((BaseInfo)data).response));
			if(getKey().substring(getKey().indexOf("/")+1).equals(((BaseInfo)data).response)){
				return true;
			}
		}
		return false;
	}
	
	/** 
	 * loadding 方式请求 json检查
	 * */
	public LoadResult check(Data data) {
		if (data == null)
			return LoadResult.ERROR;
		if(!checkJson(data))
			return LoadResult.EMPTY;
		return LoadResult.SUCCEED;
	}
	
	/** 从本地加载协议 */
	protected String loadFromLocal(int index) {
		String path = FileUtils.getCacheDir();
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new FileReader(path + getKey() + "_" + index + getGetParames()));
			String line = reader.readLine();// 第一行是时间
			Long time = Long.valueOf(line);
			if (time > System.currentTimeMillis()) {//如果时间未过期
				StringBuilder sb = new StringBuilder();
				String result;
				while ((result = reader.readLine()) != null) {
					sb.append(result);
				}
				return sb.toString();
			}
		} catch (Exception e) {
			LogUtils.e(e);
		} finally {
			IOUtils.close(reader);
		}
		return null;
	}

	/** get方式 从网络加载协议 */
	protected String loadFromNet(int index) {
		String result = null;
		HttpResult httpResult = HttpHelper.get(HttpHelper.URL + getKey() + "?index=" + index + getGetParames());
		if (httpResult != null) {
			result = httpResult.getString();
			httpResult.close();
		}
		return result;
	}
	
	/** post方式  从网络加载协议 */
	protected String loadFromNet(int index,byte[] bytes) {
		String result = null;
		HttpResult httpResult = HttpHelper.post(HttpHelper.URL + getKey() + "?index=" + index + getGetParames(), bytes);
		if (httpResult != null) {
			result = httpResult.getString();
			httpResult.close();
		}
		return result;
	}

	/** 保存到本地 */
	protected void saveToLocal(String str, int index) {
		String path = FileUtils.getCacheDir();
		BufferedWriter writer = null;
		try {
			writer = new BufferedWriter(new FileWriter(path + getKey() + "_" + index + getGetParames()));
			long time = System.currentTimeMillis() + 1000 * 60;//先计算出过期时间，写入第一行
			writer.write(time + "\r\n");
			writer.write(str.toCharArray());
			writer.flush();
		} catch (Exception e) {
			LogUtils.e(e);
		} finally {
			IOUtils.close(writer);
		}
	}

	/** Get请求 需要增加的额外参数 */
	private String getGetParames() {
		LogUtils.d(getKey()+"接口GET请求的json="+mGetParames);
		return mGetParames;
	}
	
	/** Post请求 需要增加的额外参数 json参数*/
	private byte[] getPostParames(){
		if(null==mPostParames)
			return null;
		
		//========================
//		String sdcardPathDir = android.os.Environment.getExternalStorageDirectory().getPath() + "/tempImage/json.txt";
//		 try {
//			 File file = new File(android.os.Environment.getExternalStorageDirectory().getPath() + "/tempImage");
//			 if(!file.exists()){
//				 file.mkdirs();
//			 }
//			 
//			FileOutputStream fileOutputStream = new FileOutputStream(sdcardPathDir);
//			String json = GsonUtils.bean2json(mPostParames);
//			fileOutputStream.write(json.getBytes());
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
		
		 //带上验证token
		 if(!StringUtils.isEmpty(BaseInfo.accessToken))
			 mPostParames.token=BaseInfo.accessToken;
		
		 LogUtils.d(getKey()+"接口POST请求的json="+GsonUtils.bean2json(mPostParames));

		 return GsonUtils.bean2json(mPostParames).getBytes();
	}

	/** 该协议的访问地址 */
	protected abstract String getKey();

	/** 从json中解析 */
	protected abstract Data parseFromJson(String json);
	
}
